package com.example.myapplication

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.databinding.ActivitySettingsBinding

/**
 * 设置界面
 * 允许用户配置服务器地址等参数
 */
class SettingsActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivitySettingsBinding
    private lateinit var prefs: SharedPreferences
    
    companion object {
        const val PREFS_NAME = "AppSettings"
        const val KEY_SERVER_URL = "server_url"
        const val DEFAULT_SERVER_URL = "http://45.26.199.6:8000/api"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySettingsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 设置标题栏
        supportActionBar?.apply {
            title = "服务器设置"
            setDisplayHomeAsUpEnabled(true)
        }
        
        prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        
        // 加载当前配置
        loadSettings()
        
        // 设置按钮点击事件
        binding.btnSave.setOnClickListener {
            saveSettings()
        }
        
        binding.btnReset.setOnClickListener {
            resetToDefault()
        }
        
        binding.btnTest.setOnClickListener {
            testConnection()
        }
    }
    
    /**
     * 加载当前配置
     */
    private fun loadSettings() {
        val serverUrl = prefs.getString(KEY_SERVER_URL, DEFAULT_SERVER_URL) ?: DEFAULT_SERVER_URL
        
        // 分离协议、IP和端口
        val urlPattern = Regex("(https?://)([^:]+):(\\d+)/api")
        val match = urlPattern.find(serverUrl)
        
        if (match != null) {
            val (protocol, ip, port) = match.destructured
            binding.editServerIp.setText(ip)
            binding.editServerPort.setText(port)
            binding.switchHttps.isChecked = protocol == "https://"
        } else {
            // 如果格式不匹配，使用默认值
            binding.editServerIp.setText("45.26.199.6")
            binding.editServerPort.setText("8000")
            binding.switchHttps.isChecked = false
        }
    }
    
    /**
     * 保存设置
     */
    private fun saveSettings() {
        val ip = binding.editServerIp.text.toString().trim()
        val port = binding.editServerPort.text.toString().trim()
        val useHttps = binding.switchHttps.isChecked
        
        // 验证输入
        if (ip.isEmpty()) {
            Toast.makeText(this, "请输入服务器IP地址", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (port.isEmpty()) {
            Toast.makeText(this, "请输入服务器端口", Toast.LENGTH_SHORT).show()
            return
        }
        
        val portNum = port.toIntOrNull()
        if (portNum == null || portNum < 1 || portNum > 65535) {
            Toast.makeText(this, "端口号必须在1-65535之间", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 构建URL
        val protocol = if (useHttps) "https://" else "http://"
        val serverUrl = "$protocol$ip:$port/api"
        
        // 保存到SharedPreferences
        prefs.edit().apply {
            putString(KEY_SERVER_URL, serverUrl)
            apply()
        }
        
        Toast.makeText(this, "设置已保存：$serverUrl", Toast.LENGTH_LONG).show()
        
        // 提示需要重启应用
        Toast.makeText(this, "请重启应用使新设置生效", Toast.LENGTH_LONG).show()
    }
    
    /**
     * 重置为默认设置
     */
    private fun resetToDefault() {
        prefs.edit().apply {
            putString(KEY_SERVER_URL, DEFAULT_SERVER_URL)
            apply()
        }
        
        loadSettings()
        Toast.makeText(this, "已重置为默认设置", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 测试连接
     */
    private fun testConnection() {
        val ip = binding.editServerIp.text.toString().trim()
        val port = binding.editServerPort.text.toString().trim()
        val useHttps = binding.switchHttps.isChecked
        
        if (ip.isEmpty() || port.isEmpty()) {
            Toast.makeText(this, "请先填写服务器地址和端口", Toast.LENGTH_SHORT).show()
            return
        }
        
        val protocol = if (useHttps) "https://" else "http://"
        val serverUrl = "$protocol$ip:$port/api"
        
        Toast.makeText(this, "正在测试连接到：$serverUrl", Toast.LENGTH_LONG).show()
        
        // 这里可以添加实际的网络测试逻辑
        // 为简化示例，暂时只显示提示
        Toast.makeText(this, "测试连接功能待完善，请先保存后重启应用测试", Toast.LENGTH_LONG).show()
    }
    
    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }
}

